package com.ruoyi.manage.service.impl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.manage.domain.Donation;
import com.ruoyi.manage.domain.GoodsShelves;
import com.ruoyi.manage.domain.UserDonation;
import com.ruoyi.manage.domain.vo.DonationVo;
import com.ruoyi.manage.mapper.DonationMapper;
import com.ruoyi.manage.mapper.GoodsShelvesMapper;
import com.ruoyi.manage.mapper.UserDonationMapper;
import com.ruoyi.manage.service.IUserDonationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ZhangZhongGen
 */
@Service
public class UserDonationServiceImpl implements IUserDonationService {

    @Autowired
    private UserDonationMapper  userDonationMapper;
    @Autowired
    private DonationMapper donationMapper;
    @Autowired
    private GoodsShelvesMapper goodsShelvesMapper;

    @Override
    public List<DonationVo> getCollectDonationVoList(Long userId) {
        List<UserDonation> list = userDonationMapper.selectUserDonationList(userId);
        List<DonationVo> donationVoList = donationMapper.selectDonationVoListByDonationIds(list);
        return donationVoList;
    }

    @Override
    public int insertUerDonation(UserDonation ud) {
        return userDonationMapper.insertUserDonation(ud);
    }

    /**
     * 删除收藏
     * @param ud
     * @return
     */
    public int delete(UserDonation ud) {
        return userDonationMapper.delete(ud);
    }

    /**
     * 查询是否被改用户收藏
     * @param ud
     * @return
     */
    public int selectUserDonationByUD(UserDonation ud) {
        return userDonationMapper.selectUserDonationByUD(ud);
    }

    /**
     * 存取
     * @param type
     * @param goodsShelves
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int storageOrPickup(String type, GoodsShelves goodsShelves, Long userId) {
        Donation donation = Donation.builder().id(goodsShelves.getDonationId()).build();
        donation.setUpdateTime(DateUtils.getNowDate());
        if ("storage".equals(type)) {//已入库
            donation.setDonorId(userId);
            donation.setStatus(3);
            goodsShelves.setShelfStatus(1);//货架设置为有物品
        }else if ("pickup".equals(type)) {
            donation.setReceiverId(userId);
            donation.setStatus(4);
            goodsShelves.setDonationId(null);//捐赠物设置为null
            goodsShelves.setShelfStatus(2);//货架设置为空
        }else {
            throw new RuntimeException("参数错误");
        }
        goodsShelvesMapper.updateGoodsShelves(goodsShelves);
        return donationMapper.updateDonation(donation);
    }
}
